package com.comba.nutz.boot.demo.config;

import com.comba.nutz.boot.demo.handler.AuthenctiationFailureHandler;
import com.comba.nutz.boot.demo.handler.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * @author george-hp
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    protected AuthenctiationFailureHandler authenctiationFailureHandler;

    @Autowired
    protected CustomAccessDeniedHandler customAccessDeniedHandler;

    @Value("${custom.security.check-token-url}")
    protected String checkTokenUrl;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);

        resources.tokenServices(tokenService())
                .accessDeniedHandler(customAccessDeniedHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.authorizeRequests().and().formLogin().failureHandler(authenctiationFailureHandler).permitAll();
    }

    @Bean
    public ResourceServerTokenServices tokenService() {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setClientId("android");
        tokenServices.setClientSecret("android");
        tokenServices.setCheckTokenEndpointUrl(checkTokenUrl);

        return tokenServices;
    }
}
